<?php
class Sales_Order_Item extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'sales_order_item',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	/**
	 * 更新销售单item
	 * @param $item_new
	 * @param $sales_order_id
	 * @param $handle_type
	 * @param $old_warehouse_id
	 */
	static function update($item_new, $sales_order_id, $handle_type = 'check_db', $old_warehouse_id = 0)
	{
		$item_new = Sales_Order::productBingResolved($item_new);
		$sales_order = Sales_Order::find('id=?', $sales_order_id)->asArray()->getOne();
		$item_in_db = Sales_Order_Item::find('sales_order_id=?', $sales_order_id)->asArray()->getAll();
		if ($handle_type == 'check_db')
		{
			$item_old = array();
			foreach ($item_in_db as $iid)
			{
				$item_old[$iid['id']] = $iid;
			}
			$item_create = array_diff_key($item_new, $item_old);
			$item_delete = array_diff_key($item_old, $item_new);
			$item_update = array_diff_key($item_new, $item_create);
		}
		if ($handle_type == 'all_as_new')
		{
			$item_create = $item_new;
			$item_delete = $item_in_db;
			$item_update = array();
		}
		$not_exists_product_warehouse = array();
		foreach ($item_create as $ic)
		{
			$product_warehouse = Product_Warehouse::find('product_basic.number=? and product_warehouse.warehouse_id=?', $ic['product_basic_number'], $sales_order['warehouse_id'])
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->asArray()->getOne();
			if ($product_warehouse)
			{
				$item = new Sales_Order_Item();
				$item->sales_order_id = $sales_order_id;
				$item->product_basic_id = $product_warehouse['product_basic_id'];
				$item->shop_item_id = isset($ic['shop_item_id']) ? $ic['shop_item_id'] : '';
				$item->shop_transaction_id = isset($ic['shop_transaction_id']) ? $ic['shop_transaction_id'] : '';
				$item->quantity = $ic['quantity'];
				$item->sales_price = $ic['sales_price'];
				$item->gift_flag = (isset($ic['gift_flag']) && $ic['gift_flag'] == Q::ini('custom_flag/sales_order_item_gift_flag/gift/value')) ? Q::ini('custom_flag/sales_order_item_gift_flag/gift/value') : Q::ini('custom_flag/sales_order_item_gift_flag/not/value');
				$item->fee = isset($ic['fee']) ? $ic['fee'] : 0;
				$item->save();
				$sales_order_item_id = mysql_insert_id();
				Product_Warehouse::soldQuantityIncrease($product_warehouse['id'], 0, 0, $ic['quantity']);
				if (isset($ic['attr']))
				{
					Sales_Order_Item_Attribute::update($ic['attr'], $sales_order_item_id);
				}
			}
			else
			{
				$not_exists_product_warehouse[] = $ic['product_basic_number'];
			}
		}
		foreach ($item_delete as $id)
		{
			Product_Warehouse::soldQuantityDecrease(0, $id['product_basic_id'], $old_warehouse_id, $id['quantity']);
			Sales_Order_Item_Attribute::delete($id['id']);
			Sales_Order_Item::meta()->deleteWhere('id=?', $id['id']);
		}
		foreach ($item_update as $key => $iu)
		{
			$product_warehouse = Product_Warehouse::find('product_basic.number=? and product_warehouse.warehouse_id=?', $iu['product_basic_number'], $sales_order['warehouse_id'])
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->asArray()->getOne();
			$item = Sales_Order_Item::find('id=?', $key)->getOne();
			$old_product_basic_id = $item['product_basic_id'];
			$old_quantity = $item['quantity'];
			Product_Warehouse::soldQuantityDecrease(0, $old_product_basic_id, $old_warehouse_id, $old_quantity);
			if ($product_warehouse)
			{
				$item->product_basic_id = $product_warehouse['product_basic_id'];
				$item->shop_item_id = $iu['shop_item_id'];
				$item->shop_transaction_id = $iu['shop_transaction_id'];
				$item->quantity = $iu['quantity'];
				$item->sales_price = $iu['sales_price'];
				$item->gift_flag = (isset($iu['gift_flag']) && $iu['gift_flag'] == Q::ini('custom_flag/sales_order_item_gift_flag/gift/value')) ? Q::ini('custom_flag/sales_order_item_gift_flag/gift/value') : Q::ini('custom_flag/sales_order_item_gift_flag/not/value');
				$item->fee = isset($iu['fee']) ? $iu['fee'] : 0;
				$item->save();
				Product_Warehouse::soldQuantityIncrease($product_warehouse['id'], 0, 0, $iu['quantity']);
				if (isset($iu['attr']))
				{
					Sales_Order_Item_Attribute::update($iu['attr'], $key);
				}
			}
			else
			{
				Sales_Order_Item::meta()->deleteWhere('id=?', $key);
				$not_exists_product_warehouse[] = $iu['product_basic_number'];
			}
		}
		if ($not_exists_product_warehouse)
		{
			return array('ack' => PARTIAL_FAILURE, 'message' => implode(',', $not_exists_product_warehouse) . ' not exists product warehouse');
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 删除销售单item
	 * @param $sales_order_id
	 */
	static function delete($sales_order_id)
	{
		$item = Sales_Order_Item::find('sales_order_id=?', $sales_order_id)->asArray()->getAll();
		foreach ($item as $i)
		{
			Sales_Order_Item_Attribute::delete($i['id']);
			Sales_Order_Item::meta()->deleteWhere('id=?', $i['id']);
		}
	}
	
	/**
	 * 根据销售单减少对应产品的已售待发数量
	 * @param $sales_order_id
	 */
	static function soldQauntityDecrease($sales_order_id)
	{
		$sales_order = Sales_Order::find('id=?', $sales_order_id)->asArray()->getOne();
		$item = Sales_Order_Item::find('sales_order_id=?', $sales_order_id)->asArray()->getAll();
		foreach ($item as $i)
		{
			Product_Warehouse::soldQuantityDecrease(0, $i['product_basic_id'], $sales_order['warehouse_id'], $i['quantity']);
		}
	}
	
	/**
	 * 根据销售单增加对应产品已售待发数量
	 * @param $sales_order_id
	 */
	static function soldQuantityIncrease($sales_order_id)
	{
		$sales_order = Sales_Order::find('id=?', $sales_order_id)->asArray()->getOne();
		$item = Sales_Order_Item::find('sales_order_id=?', $sales_order_id)->asArray()->getAll();
		foreach ($item as $i)
		{
			Product_Warehouse::soldQuantityIncrease(0, $i['product_basic_id'], $sales_order['warehouse_id'], $i['quantity']);
		}
	}
	
	/**
	 * 根据销售单减少对应产品可用数量
	 * @param $sales_order_id
	 */
	static function availableQuantityDecrease($sales_order_id)
	{
		$sales_order = Sales_Order::find('id=?', $sales_order_id)->asArray()->getOne();
		$item = Sales_Order_Item::find('sales_order_id=?', $sales_order_id)->asArray()->getAll();
		foreach ($item as $i)
		{
			Product_Warehouse::availableQuantityDecrease(0, $i['product_basic_id'], $sales_order['warehouse_id'], $i['quantity']);
		}
	}
	
	/**
	 * 根据销售单增加对应产品可用数量
	 * @param $sales_order_id
	 */
	static function availableQuantityIncrease($sales_order_id)
	{
		$sales_order = Sales_Order::find('id=?', $sales_order_id)->asArray()->getOne();
		$item = Sales_Order_Item::find('sales_order_id=?', $sales_order_id)->asArray()->getAll();
		foreach ($item as $i)
		{
			Product_Warehouse::availableQuantityIncrease(0, $i['product_basic_id'], $sales_order['warehouse_id'], $i['quantity']);
		}
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'sales_order_item.sales_price,sales_order_item.shop_item_id',
			'sales_order.number, sales_order.sales_time, sales_order.make_time, sales_order.shipped_time',
			'currency.rate as currency_rate, currency.symbol as currency_symbol',
			'shop.name as shop_name',
			'product_floor_price.floor_price',
			'product_basic.number as product_basic_number'
		);
		$where = Sales_Order_Item::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Sales_Order_Item::find($where)
				->joinLeft('sales_order', '', 'sales_order.id=sales_order_item.sales_order_id')
				->joinLeft('currency', '', 'currency.id=sales_order.currency_id')
				->joinLeft('shop', '', 'shop.id=sales_order.shop_id')
				->joinLeft('product_floor_price', '', 'product_floor_price.product_basic_id=sales_order_item.product_basic_id and product_floor_price.shop_id=sales_order.shop_id')
				->joinLeft('product_basic', '', 'product_basic.id=sales_order_item.product_basic_id');
			$select->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Sales_Order_Item::find($where)
				->joinLeft('sales_order', '', 'sales_order.id=sales_order_item.sales_order_id')
				->joinLeft('currency', '', 'currency.id=sales_order.currency_id')
				->joinLeft('shop', '', 'shop.id=sales_order.shop_id')
				->joinLeft('product_floor_price', '', 'product_floor_price.product_basic_id=sales_order_item.product_basic_id and product_floor_price.shop_id=sales_order.shop_id')
				->joinLeft('product_basic', '', 'product_basic.id=sales_order_item.product_basic_id');
			$select->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$sales_order_item = $select->asArray()->getAll();
		return array(
				'ack' => SUCCESS,
				'message' => '',
				'data' => $sales_order_item,
				'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = 1;
		if ( ! empty($condition['begin_make_time']))
		{
			$where .= ' and sales_order.make_time>=\'' . $condition['begin_make_time'] . '\'';
		}
		if ( ! empty($condition['end_make_time']))
		{
			$where .= ' and sales_order.make_time<=\'' . $condition['end_make_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['begin_shipped_time']))
		{
			$where .= ' and sales_order.shipped_time>=\'' . $condition['begin_shipped_time'] . '\'';
		}
		if ( ! empty($condition['end_shipped_time']))
		{
			$where .= ' and sales_order.shipped_time<=\'' . $condition['end_shipped_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['shop_id']))
		{
			if (is_array($condition['shop_id']))
			{
				$shop = implode(',', $condition['shop_id']);
				$where .= " and sales_order.shop_id in ({$shop})";
			}
			else
			{
				$where .= ' and sales_order.shop_id=\'' . $condition['shop_id'] . '\'';
			}
		}
		if ( ! empty($condition['product_number']))
		{
			$where .= ' and product_basic.number=\'' .$condition['product_number'] . '\'';
		}
		if (isset($condition['trash_status']))
		{
			if ($condition['trash_status'] == Q::ini('custom_flag/sales_order_trash_status/normal/value'))
			{
				$where .=' and (sales_order.trash_status=\'' . $condition['trash_status'] . '\' or sales_order.trash_status is null)';
			}
			else
			{
				$where .=' and sales_order.trash_status=\'' . $condition['trash_status'] . '\'';
			}
		}
		if ( ! empty($condition['is_price_monitor']))
		{
			$where .= 'and sales_order_item.shop_transaction_id is not NULL and sales_order_item.shop_transaction_id != 0 and sales_order_item.shop_transaction_id != \'\' and sales_order_item.sales_price < (product_floor_price.floor_price/sales_order.currency_rate-0.1) and sales_order.send_method=' . Q::ini('custom_flag/sales_order_send_method/normal/value');
		}
		return $where;
	}
}